package com.yuebu.yuebubtlib;

import android.app.Instrumentation;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.yuebu.yuebubtlib.bean.DeviceParameterBean;
import com.yuebu.yuebubtlib.bean.DeviceTimeBean;
import com.yuebu.yuebubtlib.bean.PersonalInfoBean;
import com.yuebu.yuebubtlib.bean.SedentaryAlarmBean;
import com.yuebu.yuebubtlib.exception.BLEException;
import com.yuebu.yuebubtlib.listener.BluetoothSignalListener;
import com.yuebu.yuebubtlib.util.BLEByteUtil;
import com.yuebu.yuebubtlib.util.BLELogUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

public class BandCommAgent {
    private static final String TAG = "BandCommAgent";
    private static BandCommAgent bandCommAgent;
    private Context mContext;
    private boolean isSupBle = true;
    private Handler mDelayHandler;
    private static String curMac;
    private boolean isScanning;
    private BluetoothAdapter bluetoothAdapter;
    private int timeout = 10000;
    private BluetoothGatt mBluetoothGatt;
    private BluetoothGattCharacteristic notifyCharacteristic;
    private BluetoothGattCharacteristic writeCharacteristic;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;
    private BluetoothSignalListener mSignalListener;
    //是否连接成功
    private boolean isConnected = false;
    private int dataCount;
    private ArrayList<Byte> sportAndSleepList;
    //计步模式下的步数
    long record_step_steps = 0l;
    //睡眠模式下的运动次数
    long sleep_mode_sport_num = 0l;
    //运动模式下的运动次数
    long sport_mode_sport_num = 0l;
    //深度睡眠
    int deepSleep = 0;
    //浅度睡眠
    int lightSleep = 0;

    //是否请求全天的运动睡眠数据
    boolean isRequestAllDay = false;
    //发送数据的队列
    LinkedBlockingQueue queue = new LinkedBlockingQueue<byte[]>(7);
    LinkedBlockingQueue pushMessageQueue = new LinkedBlockingQueue<byte[]>(3);
    private BLEScanner bleScanner;
    //重连次数
    private int reconnectionCount = 3;
    //储存卡路径
    String m_dir = Environment.getExternalStorageDirectory().getPath();
    //ota开始时间
    private Long oat_start_time = 0L;
    private String OTA_FilePath = null;
    byte[] ReadData = null;
    int CRC = 0;
    //连接超时时间
    private int BLE_CONNECT_TIMEOUT = 20000;
    //ota升级
    private BluetoothGattCharacteristic characteristic_ota_update = null;
    //ota升级服务
    private BluetoothGattService GATT_Service_ota_update = null;

    public final static String GATT_CONNECTED = "com.bluetooth.ble.GATT_CONNECTED";
    public final static String GATT_DISCONNECTED = "com.bluetooth.ble.GATT_DISCONNECTED";
    public final static String GATT_SERVICES_DISCOVERED = "com.bluetooth.ble.GATT_SERVICES_DISCOVERED";

    public final static String ACTION_DATA_CHANGE = "com.bluetooth.ble.ACTION_DATA_CHANGE";
    public final static String ACTION_DATA_READ = "com.bluetooth.ble.ACTION_DATA_READ";
    public final static String ACTION_DATA_WRITE = "com.bluetooth.ble.ACTION_DATA_WRITE";
    public final static String ACTION_DATA_CHANGED = "com.bluetooth.ble.ACTION_DATA_CHANGED";

    public final static String ACTION_RSSI_READ = "com.bluetooth.ble.ACTION_RSSI_READ";

    public static BandCommAgent getInstance(Context context) {
        if (bandCommAgent == null) {
            synchronized (BandCommAgent.class) {
                if (bandCommAgent == null) {
                    bandCommAgent = new BandCommAgent(context.getApplicationContext());
                }
            }
        }
        return bandCommAgent;
    }

    private BandCommAgent(Context context) {
        this.mContext = context;
        isSupBle = checkSDK();
        mDelayHandler = new Handler(Looper.getMainLooper());
    }

    public void setBluetoothSignalListener(BluetoothSignalListener listener) {
        this.mSignalListener = listener;
    }

    public void findAllDevices(int timeOut, BLEScanner.OnBLEScanListener listener) {
        if (bleScanner == null) {
            bleScanner = new BLEScanner(timeOut, mContext, listener);
        }
        bleScanner.startScan();
    }

    /**
     * 判断是否开启蓝牙
     *
     * @return
     */
    public boolean isOpenBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.isEnabled();
    }

    /**
     * 打开蓝牙
     *
     * @return
     */
    public boolean openBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.enable();
    }

    /**
     * 关闭蓝牙
     */
    public void closeBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.disable();
    }

    /**
     * 停止蓝牙扫描
     */
    public void stopFindAllDevices() {
        if (bleScanner != null) {
            bleScanner.stopScan();
        }
    }


    public boolean connect(String mac) {
        Log.i(TAG, "connect: " + mac);
        boolean result = false;
        stopFindAllDevices();
        close();
        if (!isBluetoothEnable()) {
            BLELogUtil.d(TAG, "Bluetooth is not enable");
            return false;
        }
        if (bluetoothAdapter == null) {
            BluetoothManager bm = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
            bluetoothAdapter = bm.getAdapter();
        }
        mDevice = bluetoothAdapter.getRemoteDevice(mac);
        if (mDevice == null) {
            BLELogUtil.e(TAG, "Bluetooth connect getRemoteDevice failure");
            result = false;
        }
        try {
            Thread.sleep(1000);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mBluetoothGatt = mDevice.connectGatt(mContext, false, gattCallback, BluetoothDevice.TRANSPORT_LE);
            } else {
                mBluetoothGatt = mDevice.connectGatt(mContext, false, gattCallback);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (mBluetoothGatt != null) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

    public boolean connect(BluetoothDevice device) {
        boolean result = false;
        if (device != null) {
            stopFindAllDevices();
            close();
            try {
                Thread.sleep(1000);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mBluetoothGatt = device.connectGatt(mContext, false, gattCallback, BluetoothDevice.TRANSPORT_LE);
                } else {
                    mBluetoothGatt = device.connectGatt(mContext, false, gattCallback);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mBluetoothGatt != null) {
                result = true;
                // mDelayHandler.postDelayed(connectTimeOutRunnable, BLE_CONNECT_TIMEOUT);
            } else {
                result = false;
            }
        } else {
            result = false;
        }
        return result;
    }

    /**
     * 连接超时处理
     */
    private Runnable connectTimeOutRunnable = new Runnable() {
        @Override
        public void run() {
            close();
            if (mSignalListener != null) {
                mSignalListener.onConnectionFailed(new BLEException(BLEException.CONNECT_TIME_OUT), Constants.CONNECTED_ERROR);
            }
        }
    };

    /**
     * 清除Gatt缓存
     */
    private void clearCacheDevice(BluetoothGatt bluetoothGatt) {
        try {
            Log.i(TAG, "BLUEPOOL refresh");
            Method method = BluetoothGatt.class.getMethod("refresh");
            if (method != null) {
                method.invoke(bluetoothGatt);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void close() {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

    public void disconnect() {
        BLELogUtil.i("主动关闭设备");
        if (mBluetoothGatt != null) {
            clearCacheDevice(mBluetoothGatt);
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
        mDelayHandler.removeCallbacksAndMessages(null);
    }

    //发送数据
    public synchronized void writeData(byte[] data) {
        if (writeCharacteristic == null) {
            if (mBluetoothGatt != null) {
                BluetoothGattService service = mBluetoothGatt.getService(Constants.SERVICE_UUID);
                if (service == null) {
                    BLELogUtil.i("BluetoothGattService==null");
                    return;
                }
                writeCharacteristic = service.getCharacteristic(Constants.WRITE_SERVICE_UUID_BASIC);
            }
        }
        writeCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        writeOneSet(mBluetoothGatt, gattCallback, writeCharacteristic, data, 0);
    }


    public static final long WAIT_TIME = 100;//两组数据之间的时间间隔
    public static final int MAX_BYTES = 20;// 蓝牙发送数据分包，每个包的最大长度为20个字节
    private int currentPosition = 0;
    private byte[] currentData;

    /**
     * 写一组数据
     *
     * @param mBluetoothGatt
     * @param gattCallback
     * @param bluetoothGattCharacteristic
     * @param data
     * @param position
     */
    private void writeOneSet(final BluetoothGatt mBluetoothGatt, final BluetoothGattCallback gattCallback, final BluetoothGattCharacteristic bluetoothGattCharacteristic, final byte[] data, int position) {
        currentPosition = position;
        currentData = data;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //两包数据间间隔一定时间
                    Thread.sleep(WAIT_TIME);
                    int sendLength = data.length - currentPosition * MAX_BYTES;
                    sendLength = sendLength > MAX_BYTES ? MAX_BYTES : sendLength;
                    byte[] sendValue = BLEByteUtil.getSubbytes(data, currentPosition * MAX_BYTES, sendLength);
                    Log.i(TAG, String.format("指令=%d,%s", currentPosition, BLEByteUtil.bytesToHexString(sendValue)));
                    if (!bluetoothGattCharacteristic.setValue(sendValue)) {
                        Log.e(TAG, "writeOneSet setValue failure");
                        //onBLEWriteDataListener.onWriteDataFailure(new BLEException(BLEException.WRITE_DATA_FAILURE));
                        return;
                    }
                    if (!mBluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic)) {
                        Log.e(TAG, "+writeOneSet writeCharacteristic failure");
                        //onBLEWriteDataListener.onWriteDataFailure(new BLEException(BLEException.WRITE_DATA_FAILURE));
                        return;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "writeOneSet e:" + e.getMessage());
                }
            }
        }).start();
    }

    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                mDelayHandler.removeCallbacks(connectTimeOutRunnable);
                try {
                    Thread.sleep(500);
                    gatt.discoverServices();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                mDelayHandler.removeCallbacks(connectTimeOutRunnable);
                //设备断开8 	设备端已经断开连接（可能是复位或者断点等原因），手机端没有收到回应，等到一定时间自动断开
                //22获取不到服务
                Log.i(TAG, "onConnectionStateChange: 设备断开了" + status);
                close();
                if (mSignalListener != null) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        isConnected = false;
                        mSignalListener.onDisconnect();
                        broadcastUpdate(GATT_DISCONNECTED, status);
                    } else {
                        isConnected = false;
                        Log.i(TAG, "中途连接断开: " + status);
                        if (reconnectionCount == 0) {
                            mSignalListener.onConnectionFailed(new BLEException("连接失败"), Constants.CONNECTED_ERROR);
                            return;
                        }
                        connect(gatt.getDevice());
                        reconnectionCount--;
                    }
                }

            } else if (newState == BluetoothGatt.STATE_CONNECTING) {
                Log.i(TAG, "onConnectionStateChange: 正在连接设备");
            }
        }

        @Override
        public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                mBluetoothGatt = gatt;
                BlueWriteDescriptor blueWriteDescriptor = new BlueWriteDescriptor();
                boolean isSuccess = blueWriteDescriptor.writeDescriptor(gatt, Constants.STR_SERVICE_UUID, Constants.STR_NOTIFY_SERVICE_UUID_ADVANCE, Constants.STR_DESCRIPTOR_CCCD);
                if (isSuccess) {
                    isConnected = true;
                    reconnectionCount = 3;
                    if (mSignalListener != null) {
                        broadcastUpdate(GATT_CONNECTED, status);
                        mSignalListener.onConnected(gatt.getDevice().getAddress());
                    }
                } else {
                    //重连一次
                    isConnected = false;
                    close();
                    if (mSignalListener != null) {
                        if (reconnectionCount == 0) {
                            mSignalListener.onConnectionFailed(new BLEException("获取服务失败"), Constants.BLUETOOTHGATTSERVICE_IS_NULL);
                            return;
                        }
                        //重新连接
                        connect(gatt.getDevice());
                        Log.i(TAG, "onServicesDiscovered: 未发现服务重连");
                        reconnectionCount--;
                    }
                }
            }
        }

        //读操作回调
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.i(TAG, "onCharacteristicRead: ");
            if (characteristic.getUuid().toString().equals(Constants.STR_BATTERY_LEVEL_UUID)) {// 获取到电量
                int battery = characteristic.getValue()[0];
                Log.i(TAG, "onCharacteristicRead: " + battery + "%");
                mSignalListener.onGetDeviceBattery(battery + "%");
            } else if (characteristic == characteristic_ota_update) {
                broadcastUpdate(ACTION_DATA_READ, status, characteristic_ota_update.getValue());
            }
        }

        //写操作的回调
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.i(TAG, "onCharacteristicWrite: ------------");
            if (characteristic.getUuid().equals(Constants.WRITE_SERVICE_UUID_BASIC)) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.i(TAG, "onCharacteristicWrite: success");
                    if (currentPosition >= 0) {
                        if ((currentPosition + 1) * MAX_BYTES >= currentData.length) {
                            //数据完全写完
                            //onBLEWriteDataListener.onWriteDataSuccess(gatt, characteristic, status);
                            return;
                        }
                        writeOneSet(gatt, gattCallback, writeCharacteristic, currentData, currentPosition + 1);
                    }
                } else {
                    Log.i(TAG, "onCharacteristicWrite: failed");
                }
            } else if (characteristic == characteristic_ota_update) {
                broadcastUpdate(ACTION_DATA_WRITE, status);
            }
        }

        //接收到设备传送过来的数据的回调
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.i(TAG, "onCharacteristicChanged: success");
            byte[] value = characteristic.getValue();
            if (characteristic.getUuid().equals(Constants.NOTIFY_SERVICE_UUID_ADVANCE)) {
                notifyCommand(value);
            }
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.i(TAG, "onDescriptorRead: ");
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);

            Log.i(TAG, "onDescriptorWrite: " + Arrays.toString(descriptor.getValue()));

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "onDescriptorWrite:开启监听成功 ");
            }

        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
            Log.i(TAG, "onReliableWriteCompleted: ");
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            Log.i(TAG, "onReadRemoteRssi: ");
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            Log.i(TAG, "onMtuChanged: ");
        }
    };

    // 发送广播消息
    private void broadcastUpdate(final String action, int value) {
        final Intent intent = new Intent(action);
        intent.putExtra("value", value);
        mContext.sendBroadcast(intent);
    }

    // 发送广播消息
    private void broadcastUpdate(final String action, int value, byte[] data) {
        final Intent intent = new Intent(action);
        intent.putExtra("value", value);
        intent.putExtra("data", data);
        mContext.sendBroadcast(intent);
    }

    int count = 0;
    boolean isStart = false;
    int sleepCount = 0;//连续睡眠的count

    private void notifyCommand(byte[] data) {
        Log.i(TAG, "onCharacteristicChanged: 接收到的数据" + Arrays.toString(data));
        byte cmd = (byte) data[0];
        int len = 0;
        byte[] val;
        boolean success = false;
        distinguishSleepData(data);
        if (mSignalListener != null) {
            switch (cmd) {
                //读取蓝牙地址成功的返回
                case Constants.READ_BLUETOOTH_DEVICE_MAC_ADDRESS_POSITIVE_BASIC:
                    val = new byte[6];
                    System.arraycopy(data, 2, val, 0, 6);
                    String mac = BLEByteUtil.bytesToMac(val);
                    if (mac != null) {
                        mSignalListener.onReceiveMacAddress(mac);
                    }
                    break;
                //读取设备固件版本
                case Constants.READ_BLUETOOTH_DEVICE_FIRMWARE_VERSION_POSITIVE_BASIC:
                    if (data.length == 20) {
                        mSignalListener.onReceiveDeviceFirmwareVersion("V" + data[17] + "-" + data[18]);
                    }
                    break;
                //设置手环时间成功
                case Constants.SET_DEVICE_TIME_POSITIVE_BASIC:
                    Log.i(TAG, "设置手环时间成功");
                    mSignalListener.onSetDeviceTimeResponse(true);
                    break;
                case Constants.SET_DEVICE_TIME_NEGATIVE_BASIC:
                    mSignalListener.onSetDeviceTimeResponse(false);
                    break;
                //读取手环时间成功
                case Constants.READ_DEVICE_TIME_POSITIVE_BASIC:
//                    Log.i(TAG, "读取设备时间: " + Arrays.toString(data));
                    val = new byte[6];
                    //星期几
                    int week = data[8] & 0xff;
                    System.arraycopy(data, 2, val, 0, 6);
                    String str = Arrays.toString(val);
                    String s = str.substring(1, str.length() - 1).replace(", ", ":");
                    Log.i(TAG, "手环时间: " + s);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy:MM:dd:HH:mm:ss");
                    Date date = null;
                    try {
                        date = simpleDateFormat.parse(s);
                        long ts = date.getTime();
                        mSignalListener.onReadDeviceTime(new DeviceTimeBean(ts, week));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    break;
                //清除手环数据成功
                case Constants.CLEAR_DATA_POSITIVE_BASIC:
                    mSignalListener.onClearDataResponse(true);
                    break;
                //设置用户信息成功
                case Constants.SET_PERSONAL_INFO_POSITIVE_BASIC:
                    mSignalListener.onSetPersonalInfoResponse(true);
                    break;
                //获取运动和睡眠数据成功
                case Constants.READ_SPORT_AND_SLEEP_DATA_POSITIVE_BASIC:
                    int dataLength = (data[1] & 0xff) + 3;
                    dataCount = dataLength % 20 > 0 ? dataLength / 20 + 1 : dataLength / 20;
                    if (sportAndSleepList == null) {
                        sportAndSleepList = new ArrayList();
                    }
                    for (byte b : data) {
                        sportAndSleepList.add(b);
                    }
                    dataCount--;
                    if (!queue.isEmpty()) {
                        try {
                            Thread.sleep(200);
                            writeData((byte[]) queue.poll());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //设置久坐提醒成功
                case Constants.SET_SEDENTARY_ALARM_POSITIVE:
                    mSignalListener.onSetSedentaryAlarm(true);
                    break;
                //设置久坐提醒失败
                case Constants.SET_SEDENTARY_ALARM_NEGATIVE:
                    mSignalListener.onSetSedentaryAlarm(false);
                    break;
                case Constants.SET_DEVICE_PARAMETER_POSITIVE:
                    Log.i(TAG, "设置手环参数成功");
                    mSignalListener.onSetDeviceParameterResponse(true);
                case Constants.SET_DEVICE_PARAMETER_NEGATIVE:
                    mSignalListener.onSetDeviceParameterResponse(false);
                    break;
                case Constants.CMD_TAKE_PHOTO_BASIC:
                    Log.i(TAG, "摇一摇拍照成功");
                    mSignalListener.onTakePhotoSuccess();
                    break;
                case Constants.ANTI_LOST_POSITIVE_BASIC:
                    Log.i(TAG, "查找手环成功");
                    mSignalListener.onFindDeviceSuccess();
                    break;
                case Constants.READ_DEVICE_REAL_STEP_POSITIVE_BASIC:
                    long i0 = (((long) data[2] << 16) & 0xff0000);
                    long i1 = (((long) data[3] << 8) & 0xff00);
                    long i2 = data[4] & 0xff;
                    mSignalListener.onReadDeviceRealStep(i0 + i1 + i2);
                    break;
                case Constants.READ_REAL_HEART_RATE_POSITIVE:
                    Log.i(TAG, "读取心率成功");
                    byte sensorMode = data[2];//传感器模式
                    if (sensorMode == 0x80) {
                        mSignalListener.onReadHeartRateResponse(data[6] & 0xff);
                    } else if (sensorMode == 0x40) {
                        mSignalListener.onReadBloodpressure(data[6] & 0xff, data[7] & 0xff);
                    }
                    break;
                case Constants.READ_REAL_HEART_RATE_NEGATIVE:
                    Log.i(TAG, "读取心率失败");
                    break;
                case Constants.CMD_APP_WARN_BAND_BASIC:
                    Log.i(TAG, "app推送消息成功");
                    if (!pushMessageQueue.isEmpty()) {
                        writeData((byte[]) pushMessageQueue.poll());
                    }
                    break;
                case Constants.CONTROL_BAND_POSITIVE_ABVANCE:
                    Log.i(TAG, "控制手环成功");
                    mSignalListener.onControlDeviceResponse(true);
                    break;
            }
        }
    }

    private void distinguishSleepData(byte[] data) {
        if (sportAndSleepList != null && dataCount > 0) {
            for (byte b : data) {
                sportAndSleepList.add(b);
            }
            dataCount--;
            if (dataCount == 0) {
                Byte[] result = sportAndSleepList.toArray(new Byte[sportAndSleepList.size()]);
                Log.i(TAG, "result.length: " + result.length);
                int sumData = 0;//连续睡眠3次的时间
                for (int i = 6; i < result.length - 1; i++) {
                    if (i % 6 == 0) {
                        //第15位
                        int sportModeFlag1 = (result[i] >> 7) & 0xff;
                        //第14位
                        int sportModeFlag2 = ((result[i] << 1) >> 7) & 0xff;

                        if (sportModeFlag1 == 0 && sportModeFlag2 == 0) {//计步模式
                            record_step_steps += ((long) ((result[i] << 8) & 0x3f00)) + (long) (result[i + 1] & 0xff);
                        } else if (sportModeFlag1 == 0 && sportModeFlag2 == 1) {//睡眠模式
                            long sleepData = ((long) ((result[i] << 8) & 0x3f00)) + (long) (result[i + 1] & 0xff);
                            Log.i(TAG, "sleepData: " + sleepData);
                            if (isStart) {
                                if (sleepData <= 4) {
                                    deepSleep++;
                                } else if (sleepData > 4 && sleepData <= 30) {
                                    lightSleep++;
                                } else if (sleepData > 30) {
                                    isStart = false;
                                    break;
                                }
                                sleepCount++;
                                if (sleepCount <= 6) {
                                    sumData += sleepData;
                                    if (sleepCount == 6) {
                                        if (sumData == 0) {
                                            isStart = false;
                                            break;
                                        }
                                        sleepCount = 0;
                                    }
                                }
                                sleep_mode_sport_num += sleepData;
                            } else {
                                sleepCount++;
                                if (sleepCount <= 3) {
                                    sumData += sleepData;
                                    if (sleepData <= 4) {
                                        deepSleep++;
                                    } else if (sleepData > 4 && sleepData <= 30) {
                                        lightSleep++;
                                    } else if (sleepData > 30) {
                                        isStart = false;
                                        sleepCount = 0;
                                        break;
                                    }
                                    if (sleepCount == 3) {
                                        if (sumData == 0) {
                                            isStart = false;
                                        } else if (sumData > 0) {
                                            isStart = true;
                                        }
                                        sleepCount = 0;
                                    }
                                }
                            }
                        } else if (sportModeFlag1 == 1 && sportModeFlag2 == 0) {//运动模式
                            sleepCount = 0;
                            sport_mode_sport_num += ((long) ((result[i] << 8) & 0x3f00)) + (long) (result[i + 1] & 0xff);
                        }
                    }
                }
                if (isRequestAllDay) {
                    if (count == 7) {
                        Log.i(TAG, "record_step_steps: " + record_step_steps + "sleep_mode_sport_num: " + sleep_mode_sport_num + "sport_mode_sport_num: " + sport_mode_sport_num);
                        mSignalListener.onReadDeviceSportAndSleepDataResponse(record_step_steps, deepSleep * 10, lightSleep * 10);
                        record_step_steps = 0;
                        sleep_mode_sport_num = 0;
                        sport_mode_sport_num = 0;
                        deepSleep = 0;
                        lightSleep = 0;
                        isRequestAllDay = false;
                        count = 0;
                    } else {
                        count++;
                    }
                } else {
                    mSignalListener.onReadDeviceSportAndSleepDataResponse(record_step_steps, deepSleep * 10, lightSleep * 10);
                    record_step_steps = 0;
                    sleep_mode_sport_num = 0;
                    sport_mode_sport_num = 0;
                    deepSleep = 0;
                    lightSleep = 0;
                }
                sportAndSleepList = null;
            }
        }
    }


    /**
     * 检查SDK版本，是否支持BLE
     *
     * @return true--支持;false--不支持;
     */
    private static boolean checkSDK() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    /**
     * 蓝牙是否可用
     *
     * @return true:可用;false:不可用
     */
    public boolean isBluetoothEnable() {
        if (isSupportBluetooth()) {
            return BluetoothAdapter.getDefaultAdapter().isEnabled();
        }
        return false;
    }

    /**
     * 是否支持蓝牙
     *
     * @return true:支持;false:不支持
     */
    public boolean isSupportBluetooth() {
        return BluetoothAdapter.getDefaultAdapter() != null;
    }

    /**
     * 读取运动和睡眠数据
     */
    public void readSportAndSleepData(int week, int hour) {
        if (isConnected) {
            byte[] cmd = new byte[6];
            cmd[0] = Constants.CMD_READ_SPORT_AND_SLEEP_DATA_BASIC;
            cmd[1] = (byte) 0x03;
            cmd[2] = (byte) week;
            cmd[3] = (byte) hour;
            cmd[4] = (byte) 0x03;
            cmd[5] = getChecksum(cmd);
            writeData(cmd);
        }

    }

    private byte[] makeReadSportAndSleepCmd(int week, int hour) {
        byte[] cmd = new byte[6];
        cmd[0] = Constants.CMD_READ_SPORT_AND_SLEEP_DATA_BASIC;
        cmd[1] = (byte) 0x03;
        cmd[2] = (byte) week;
        cmd[3] = (byte) hour;
        cmd[4] = (byte) 0x03;
        cmd[5] = getChecksum(cmd);
        return cmd;
    }

    /**
     * 检测血压
     *
     * @param isStart 是否开始检测
     * @param readNum 检测次数
     */
    public void readCurrentBloodpressure(boolean isStart, int readNum) {
        if (isConnected) {
            int intStart = 1;
            if (isStart == true) {
                intStart = 1;
            } else {
                intStart = 0;
            }
            byte[] cmd = new byte[20];
            cmd[0] = Constants.CMD_READ_REAL_HEART_RATE;
            cmd[1] = (byte) 0x11;
            cmd[2] = (byte) 0x40;
            cmd[3] = (byte) 0x00;
            cmd[4] = (byte) 0x00;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) intStart;
            cmd[7] = (byte) intStart;
            cmd[8] = (byte) readNum;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            cmd[19] = getChecksum(cmd);
            writeData(cmd);

        }
    }

    /**
     * 读取手环实时心率数据
     *
     * @param isStart 是否开始
     * @param readNum 读取次数
     */

    public void readRealHeartRate(boolean isStart, int readNum) {
        if (isConnected) {
            int intStart = 1;
            if (isStart == true) {
                intStart = 1;
            } else {
                intStart = 0;
            }
            byte[] cmd = new byte[20];
            cmd[0] = Constants.CMD_READ_REAL_HEART_RATE;
            cmd[1] = (byte) 0x11;
            cmd[2] = (byte) 0x80;
            cmd[3] = (byte) 0x00;
            cmd[4] = (byte) 0x00;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) intStart;
            cmd[7] = (byte) intStart;
            cmd[8] = (byte) readNum;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            cmd[19] = getChecksum(cmd);
            writeData(cmd);
        }
    }


    /**
     * 读取运动和睡眠全天数据
     */
    public void readSportAndSleepData(final int week) {
        if (isConnected) {
            isRequestAllDay = true;
            for (int i = 0; i < 8; i++) {
                if (i == 0) {
                    readSportAndSleepData(week, 0);
                } else {
                    queue.offer(makeReadSportAndSleepCmd(week, i * 3));
                }
            }
        }
    }

    /**
     * 设置个人信息
     */
    public void setPersonalInfo(PersonalInfoBean bean) {
        if (isConnected) {
            String str = BLEByteUtil.int2HexString(bean.getUser_step_target());
            int v1 = new BigInteger(str.substring(0, 2), 10).intValue();
            int v2 = new BigInteger(str.substring(2, 4), 10).intValue();
            int v3 = new BigInteger(str.substring(4, 6), 10).intValue();

            byte[] cmd = new byte[50];
            cmd[0] = Constants.CMD_SET_PERSONAL_INFO_BASIC;
            cmd[1] = (byte) 0x2f;
            //Alarm1--------start
            cmd[2] = (byte) bean.getAlarm1_open();
            cmd[3] = (byte) bean.getAlerm1_hour();
            cmd[4] = (byte) bean.getAlerm1_minute();
            cmd[5] = (byte) bean.getAlerm1_reminding();
            cmd[6] = (byte) bean.getAlerm1_weeks();
            //Alarm1--------end

            //Alarm2--------start
            cmd[7] = (byte) bean.getAlarm2_open();
            cmd[8] = (byte) bean.getAlerm2_hour();
            cmd[9] = (byte) bean.getAlerm2_minute();
            cmd[10] = (byte) bean.getAlerm2_reminding();
            cmd[11] = (byte) bean.getAlerm2_weeks();
            //Alarm2--------end

            //Alarm3--------start
            cmd[12] = (byte) bean.getAlarm3_open();
            cmd[13] = (byte) bean.getAlerm3_hour();
            cmd[14] = (byte) bean.getAlerm3_minute();
            cmd[15] = (byte) bean.getAlerm3_reminding();
            cmd[16] = (byte) bean.getAlerm3_weeks();
            //Alarm3--------end

            //Alarm4--------start
            cmd[17] = (byte) bean.getAlarm4_open();
            cmd[18] = (byte) bean.getAlerm4_hour();
            cmd[19] = (byte) bean.getAlerm4_minute();
            cmd[20] = (byte) bean.getAlerm4_reminding();
            cmd[21] = (byte) bean.getAlerm4_weeks();
            //Alarm4----------end

            //Idle Alert---------start
            cmd[22] = (byte) 0x00;
            cmd[23] = (byte) 0x00;
            cmd[24] = (byte) 0x00;
            cmd[25] = (byte) 0x00;
            cmd[26] = (byte) 0x00;
            //Idle Alert---------end

            //Activity Alert---------start
            cmd[27] = (byte) 0x00;
            cmd[28] = (byte) 0x00;
            cmd[29] = (byte) 0x00;
            cmd[30] = (byte) 0x00;
            cmd[31] = (byte) 0x00;
            cmd[32] = (byte) 0x00;
            cmd[33] = (byte) 0x00;
            //Activity Alert---------end

            //other----------start
            cmd[34] = (byte) bean.getUser_sex();
            cmd[35] = (byte) bean.getUser_height();
            cmd[36] = (byte) bean.getUser_weight();
            cmd[37] = (byte) bean.getUser_stride_walk();
            cmd[38] = (byte) bean.getUser_stride_run();
            cmd[39] = (byte) bean.getUser_sleep_start_hour();
            cmd[40] = (byte) bean.getUser_sleep_start_mins();
            cmd[41] = (byte) bean.getUser_sleep_end_hour();
            cmd[42] = (byte) bean.getUser_sleep_end_mins();
            cmd[43] = (byte) v1;
            cmd[44] = (byte) v2;
            cmd[45] = (byte) v3;
            cmd[46] = (byte) 0x00;
            cmd[47] = (byte) 0x00;
            cmd[48] = (byte) 0x00;
            //other-----------end

            //checksum
            cmd[49] = getChecksum(cmd);
            writeData(cmd);
        }

    }


    //清除数据
    public void clearData() {
        if (isConnected) {
            byte[] cmd = new byte[3];
            cmd[0] = Constants.CMD_CLEAR_DATA_BASIC;
            cmd[1] = (byte) 0x00;
            cmd[2] = (byte) 0x00;
            writeData(cmd);
        }

    }

    //获取蓝牙mac地址
    public void getDeviceMacAddress() {
        if (isConnected) {
            byte[] cmd = new byte[3];
            cmd[0] = Constants.CMD_READ_BLUETOOTH_DEVICE_MAC_ADDRESS_BASIC;
            cmd[1] = (byte) 0x00;
            cmd[2] = (byte) 0x00;
            writeData(cmd);
        }

    }


    //获取固件版本
    public void getDeviceFirmwareVersion() {
        if (isConnected) {
            byte[] cmd = new byte[3];
            cmd[0] = Constants.CMD_READ_BLUETOOTH_DEVICE_FIRMWARE_VERSION_BASIC;
            cmd[1] = (byte) 0x00;
            cmd[2] = (byte) 0x00;
            Log.i(TAG, "getDeviceFirmwareVersion: " + Arrays.toString(cmd));
            writeData(cmd);
        }

    }

    //查找手环
    public void findDevice(boolean isFind) {
        if (isConnected) {
            byte[] cmd = new byte[4];
            cmd[0] = Constants.CMD_ANTI_LOST_BASIC;
            cmd[1] = (byte) 0x01;
            if (isFind) {
                cmd[2] = (byte) 0x01;
            } else {
                cmd[2] = (byte) 0xa1;
            }
            cmd[3] = (byte) (0x00 ^ cmd[2]);
            writeData(cmd);
        }

    }

    //设置手环时间
    public void setDeviceTime(Long currentTime) {
        if (isConnected) {
            Calendar calendar = Calendar.getInstance();
            //返回值1-7分别代表周天到周六都是减一
            int i = calendar.get(calendar.DAY_OF_WEEK) - 1;
            if (i == 0) {
                i = 7;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yy:MM:dd:HH:mm:ss");
            String format = sdf.format(new Date(currentTime));
            String[] split = format.split(":");
            int year = new BigInteger(split[0], 10).intValue();
            int month = new BigInteger(split[1], 10).intValue();
            int date = new BigInteger(split[2], 10).intValue();
            int hour = new BigInteger(split[3], 10).intValue();
            int minute = new BigInteger(split[4], 10).intValue();
            int second = new BigInteger(split[5], 10).intValue();
            byte[] cmd = new byte[10];
            cmd[0] = Constants.CMD_SET_DEVICE_TIME_BASIC;
            cmd[1] = (byte) 0x07;
            cmd[2] = (byte) year;
            cmd[3] = (byte) month;
            cmd[4] = (byte) date;
            cmd[5] = (byte) hour;
            cmd[6] = (byte) minute;
            cmd[7] = (byte) second;
            cmd[8] = (byte) i;
            cmd[9] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    private byte getChecksum(byte[] cmd) {
        byte checksum = (byte) 0x00;
        for (int i = 2; i < cmd.length - 1; i++) {
            checksum ^= cmd[i];
        }
        return checksum;
    }

    //读取手环时间
    public void readDeviceTime() {
        if (isConnected) {
            byte[] cmd = new byte[3];
            cmd[0] = Constants.CMD_READ_DEVICE_TIME_BASIC;
            cmd[1] = (byte) 0x00;
            cmd[2] = (byte) 0x00;
            writeData(cmd);
        }

    }

    //获取设备电量
    public void getDeviceBattery() {
        if (mBluetoothGatt != null) {
            BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(Constants.STR_BATTERY_SERVICE_UUID));
            if (service == null) {
                BLELogUtil.i("BluetoothGattService==null");
                return;
            }
            BluetoothGattCharacteristic notifyCharacteristic = service.getCharacteristic(UUID.fromString(Constants.STR_BATTERY_LEVEL_UUID));
            if (notifyCharacteristic == null) {
                BLELogUtil.i("notifyCharacteristic == null");
                return;
            }
            mBluetoothGatt.readCharacteristic(notifyCharacteristic);
        }
    }

    //手环控制拍照CMD_TAKE_PHOTO_BASIC
    public void takePhoto(boolean isOpen) {
        if (isConnected) {
            byte state = (byte) 0x00;
            if (isOpen) {
                state = (byte) 0x01;
            } else {
                state = (byte) 0x02;
            }
            byte[] cmd = new byte[4];
            cmd[0] = Constants.CMD_TAKE_PHOTO_BASIC;
            cmd[1] = (byte) 0x01;
            cmd[2] = state;
            cmd[3] = state;
            writeData(cmd);
        }
    }

    //设置久坐提醒
    public void setSedentaryAlarm(SedentaryAlarmBean bean) {
        if (isConnected) {
            byte[] cmd = new byte[8];
            cmd[0] = Constants.CMD_SEDENTARY_BASIC;
            cmd[1] = (byte) 0x05;
            cmd[2] = (byte) bean.getIsOpen();
            cmd[3] = (byte) bean.getStartHour();
            cmd[4] = (byte) bean.getEndHour();
            cmd[5] = (byte) bean.getDetectionTime();
            cmd[6] = (byte) bean.getRepeatCycle();
            cmd[7] = getChecksum(cmd);
            writeData(cmd);
        }

    }

    //设置手环参数
    public void setDeviceParameter(DeviceParameterBean bean) {
        if (isConnected) {
            byte[] cmd = new byte[18];
            cmd[0] = Constants.CMD_SET_DEVICE_PARAMETER;
            cmd[1] = (byte) 0x0f;
            cmd[2] = (byte) bean.getTimeType();
            cmd[3] = (byte) bean.getTemperature();
            cmd[4] = (byte) bean.getOffScreenTime();
            cmd[5] = (byte) bean.getSomehowTheScreen();
            cmd[6] = (byte) bean.getMeasurementType();
            cmd[7] = (byte) bean.getShockToggle();
            cmd[8] = (byte) bean.getBrightScreenToggle();
            cmd[9] = (byte) bean.getLanguageType();
            cmd[10] = (byte) bean.getNotDisturbMode();
            cmd[11] = (byte) bean.getNotDisturbStartHour();
            cmd[12] = (byte) bean.getNotDisturbStartMinute();
            cmd[13] = (byte) bean.getNotDisturbEndHour();
            cmd[14] = (byte) bean.getNotDisturbEndMinute();
            cmd[15] = (byte) bean.getScreenOrientation();
            cmd[16] = (byte) bean.getDateDispalyType();
            cmd[17] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    //获取手环实时步数
    public void getDeviceRealStep() {
        if (isConnected) {
            byte[] cmd = new byte[4];
            cmd[0] = Constants.CMD_READ_DEVICE_REAL_STEP_BASIC;
            cmd[1] = (byte) 0x01;
            cmd[2] = (byte) 0x08;
            cmd[3] = (byte) 0x08;
            writeData(cmd);
        }
    }


    //app推送消息到手环
    public void appPushMessageToDevice(int messageType, String notificationTitle, String notificationContent) {
        if (isConnected) {
            if (!TextUtils.isEmpty(notificationContent) && !TextUtils.isEmpty(notificationTitle)) {
                try {
                    String notificationTitleStr = new String(notificationTitle.getBytes(), "utf-8");
                    String notificationContentStr = new String(notificationContent.getBytes(), "utf-8");
                    byte[] ContentChars = notificationContentStr.getBytes();
                    byte[] titleChars = notificationTitleStr.getBytes();
                    for (int i = 0; i < 4; i++) {
                        if (i == 0) {
                            byte[] cmd0 = new byte[6];
                            cmd0[0] = Constants.CMD_APP_WARN_BAND_BASIC;
                            cmd0[1] = (byte) 0x03;
                            cmd0[2] = (byte) 0x00;
                            cmd0[3] = (byte) 0x00;
                            cmd0[4] = (byte) messageType;
                            cmd0[5] = getChecksum(cmd0);
                            writeData(cmd0);
                        } else if (i == 1) {
                            byte[] cmd1 = new byte[titleChars.length + 4];
                            cmd1[0] = Constants.CMD_APP_WARN_BAND_BASIC;
                            cmd1[1] = (byte) (titleChars.length + 1);
                            cmd1[2] = (byte) 0x01;
                            for (int x = 0; x < titleChars.length; x++) {
                                cmd1[3 + x] = titleChars[x];
                            }
                            cmd1[titleChars.length + 3] = getChecksum(cmd1);
                            Log.i(TAG, "appPushMessageToDevice: 1" + Arrays.toString(cmd1));
                            pushMessageQueue.add(cmd1);
                        } else if (i == 2) {
                            byte[] cmd2 = new byte[ContentChars.length + 4];
                            cmd2[0] = Constants.CMD_APP_WARN_BAND_BASIC;
                            cmd2[1] = (byte) (ContentChars.length + 1);
                            cmd2[2] = (byte) 0x02;
                            // cmd2[3] = (byte) 0x00;
                            for (int x = 0; x < ContentChars.length; x++) {
                                cmd2[3 + x] = ContentChars[x];
                            }
                            cmd2[ContentChars.length + 3] = getChecksum(cmd2);
                            Log.i(TAG, "appPushMessageToDevice: 2" + Arrays.toString(cmd2));
                            pushMessageQueue.add(cmd2);
                        } else if (i == 3) {
                            byte[] cmd3 = new byte[4];
                            cmd3[0] = Constants.CMD_APP_WARN_BAND_BASIC;
                            cmd3[1] = (byte) 0x01;
                            cmd3[2] = (byte) 0x03;
                            cmd3[3] = getChecksum(cmd3);
                            Log.i(TAG, "appPushMessageToDevice: 3" + Arrays.toString(cmd3));
                            pushMessageQueue.add(cmd3);
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 设置提醒开关类型
     *
     * @param pushType 开关类型
     */
    public void setPushTypeSwitch(PushType pushType) {
        if (isConnected) {
            //用于位移
            byte def = (byte) 0x80;
            byte[] cmd = new byte[20];
            cmd[0] = (byte) 0xff;
            cmd[1] = (byte) 0x11;
            cmd[2] = (byte) 0x00;
            cmd[3] = (byte) 0x00;
            cmd[4] = (byte) 0x00;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) 0x00;
            cmd[7] = (byte) 0x00;
            cmd[8] = (byte) 0x00;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            switch (pushType) {
                case PUSH_TYPE_CALL:
                    cmd[3] = def;
                    break;
                case PUSH_TYPE_MESSAGE:
                    cmd[3] = (byte) ((-def + 1) >> 1);
                    break;
                case PUSH_TYPE_MAIL:
                    cmd[3] = (byte) ((-def + 1) >> 2);
                    break;
                case PUSH_TYPE_SCHEDULE:
                    cmd[3] = (byte) ((-def + 1) >> 3);
                    break;
                case PUSH_TYPE_LOW:
                    cmd[3] = (byte) ((-def + 1) >> 4);
                    break;
                case PUSH_TYPE_FACEBOOK:
                    cmd[3] = (byte) ((-def + 1) >> 5);
                    break;
                case PUSH_TYPE_TWITTER:
                    cmd[3] = (byte) ((-def + 1) >> 6);
                    break;
                case PUSH_TYPE_WECHAT:
                    cmd[4] = def;
                    break;
                case PUSH_TYPE_QQ:
                    cmd[4] = (byte) ((-def + 1) >> 1);
                    break;
                case PUSH_TYPE_SKYPE:
                    cmd[4] = (byte) ((-def + 1) >> 2);
                    break;
                case PUSH_TYPE_LINE:
                    cmd[4] = (byte) ((-def + 1) >> 3);
                    break;
                case PUSH_TYPE_WHATSAPP:
                    cmd[4] = (byte) ((-def + 1) >> 4);
                    break;
                case PUSH_TYPE_MISSED_CALL:
                    cmd[4] = (byte) ((-def + 1) >> 5);
                    break;
                case PUSH_TYPE_MISSED_MESSAGE:
                    cmd[4] = (byte) ((-def + 1) >> 6);
                    break;
                case PUSH_TYPE_NAME:
                    cmd[4] = (byte) ((-def + 1) >> 7);
                    break;
            }
            cmd[19] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    /**
     * 打开所有提醒
     */
    public void openAllPushSwitch() {
        if (isConnected) {
            byte[] cmd = new byte[20];
            cmd[0] = Constants.CMD_CONTROL_BAND_ABVANCE;
            cmd[1] = (byte) 0x11;
            cmd[2] = (byte) 0x00;
            cmd[3] = (byte) 0xff;
            cmd[4] = (byte) 0xff;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) 0x00;
            cmd[7] = (byte) 0x00;
            cmd[8] = (byte) 0x00;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            cmd[19] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    /**
     * 关闭手环
     */
    public void closeDevice() {
        if (isConnected) {
            byte[] cmd = new byte[20];
            cmd[0] = Constants.CMD_CONTROL_BAND_ABVANCE;
            cmd[1] = (byte) 0x01;
            cmd[2] = (byte) 0x01;
            cmd[3] = (byte) 0x00;
            cmd[4] = (byte) 0x00;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) 0x00;
            cmd[7] = (byte) 0x00;
            cmd[8] = (byte) 0x00;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            cmd[19] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    /**
     * 重启手环
     */
    public void restartDevice() {
        if (isConnected) {
            byte[] cmd = new byte[20];
            cmd[0] = Constants.CMD_CONTROL_BAND_ABVANCE;
            cmd[1] = (byte) 0x01;
            cmd[2] = (byte) 0x02;
            cmd[3] = (byte) 0x00;
            cmd[4] = (byte) 0x00;
            cmd[5] = (byte) 0x00;
            cmd[6] = (byte) 0x00;
            cmd[7] = (byte) 0x00;
            cmd[8] = (byte) 0x00;
            cmd[9] = (byte) 0x00;
            cmd[10] = (byte) 0x00;
            cmd[11] = (byte) 0x00;
            cmd[12] = (byte) 0x00;
            cmd[13] = (byte) 0x00;
            cmd[14] = (byte) 0x00;
            cmd[15] = (byte) 0x00;
            cmd[16] = (byte) 0x00;
            cmd[17] = (byte) 0x00;
            cmd[18] = (byte) 0x00;
            cmd[19] = getChecksum(cmd);
            writeData(cmd);
        }
    }

    public void sendData(byte[] data) {
        if (characteristic_ota_update == null) {
            if (mBluetoothGatt != null) {
                GATT_Service_ota_update = mBluetoothGatt.getService(Constants.OTA_UPDATE_SERVICE_UUID);
                if (GATT_Service_ota_update == null) {
                    return;
                }
                characteristic_ota_update = GATT_Service_ota_update.getCharacteristic(Constants.OTA_UPDATE_CHARACTERISTIC_UUID);
                if (characteristic_ota_update == null) {
                    return;
                }
            } else {
                return;
            }
        }
        characteristic_ota_update.setValue(data);
        characteristic_ota_update.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        mBluetoothGatt.writeCharacteristic(characteristic_ota_update);
    }

    public void sendData(byte[] data, int writeType) {
        if (characteristic_ota_update == null) {
            if (mBluetoothGatt != null) {
                GATT_Service_ota_update = mBluetoothGatt.getService(Constants.OTA_UPDATE_SERVICE_UUID);
                if (GATT_Service_ota_update == null) {
                    return;
                }
                characteristic_ota_update = GATT_Service_ota_update.getCharacteristic(Constants.OTA_UPDATE_CHARACTERISTIC_UUID);
                if (characteristic_ota_update == null) {
                    return;
                }
            } else {
                return;
            }
        }
        characteristic_ota_update.setValue(data);
        characteristic_ota_update.setWriteType(writeType);
        mBluetoothGatt.writeCharacteristic(characteristic_ota_update);
    }

    public void entryOTAMode() {
        if (isConnected) {
            byte[] cmd = new byte[4];
            cmd[0] = (byte) 0xFC;
            cmd[1] = 0x01;
            cmd[2] = 0x00;
            cmd[3] = 0x00;
            writeData(cmd);
        }
    }

    public void receiveData() {
        if (characteristic_ota_update != null) {
            mBluetoothGatt.readCharacteristic(characteristic_ota_update);
        }
    }

//    public  void readVer(String mac, final BleCallBack runnable){
//        this.mClient.read(mac, DEVICE_SOFTVER_SERVICE, DEVICE_SOFTVER_CHARAMTUUID, new BleReadResponse() {
//            @Override
//            public void onResponse(int code, byte[] data) {
//                try {
//                    String s_utf8 = new String(data,"UTF-8");
//                    BluetoothLog.i(s_utf8);
//                    runnable.receive(s_utf8);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        });
//    }
}

